<?php

namespace App\Http\Controllers\Home;
use Hash;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests\UserInsertRequest;
use Mail;
use App\Http\Controllers\Admin\CateController;
class UserController extends Controller
{
    public function getIndex(Request $request)
    {	
      $cates = CateController::getCatesByPid(0);
      //获取用户id信息
    	$user = DB::table('user')->where('id',session('uid'))->first();
    	//dd(session('uid'));
    	//解析模板
    	return view('home.user.index',['user'=>$user,'cates'=>$cates]);
    }

    //数据处理
    public function postUpdate(Request $request)
    { 
      $this->validate($request,[
          'username' => 'required|regex:/\w{6,18}/',
          'email'=>'required|email',
          ],[
           'username.required' => '用户名不能为空',
           'email.required' => '邮箱不能为空',
           'username.regex'  => '用户名需要6-18位字母数字下划线组成',
           'email.email'  => '邮箱格式不正确',
        ]);
    	$data = $request->only('username','phone','addr','email','pic');
    	//获取id
    	$id = $request->input('id');
    	//文件上传
    	$data['pic'] = $this->upload($request,'pic'); 
    	//上传数据
    	$res = DB::table('user')->where('id',$id)->update($data);
    	if($res){
    		//修改成功
    		return redirect('/home/user/index')->with('success','资料修改成功');
    	}else{
    		return back()->with('error','资料修改失败');
    	}
    }

    //封装方法 进行文件上传
    public function upload($request,$filename)
   {
   	 if($request->hasFile($filename)){

   	 	//获取文件后缀名
   	 	$suffix = $request->file($filename)->getClientOriginalExtension(); 
   	 	//获取随机文件名
   	 	$name = md5(time().rand(1,9999));

   	 	$request->file($filename)->move('./uploads/',$name.'.'.$suffix);

   	 	return '/uploads/'.$name.'.'.$suffix;

   	 }else{
   	 	return '没有文件上传';
   	 }
   }
}
